from flask import Flask, render_template, jsonify
import os
import time
import threading
from flask import Flask, render_template, jsonify
from utils.api_client import ApiClient

app = Flask(__name__)
app.config.from_object('config.Config')

# 初始化API客户端
token_expires_at = 0
api_client = None
voting_data = {}

# 获取或更新Token
def get_api_client():
    global token_expires_at, api_client
    current_time = time.time()
    # 每20分钟更新一次Token
    if token_expires_at < current_time:
        api_client = ApiClient(app.config['API_URL'], app.config['API_KEY'])
        token_expires_at = current_time + 20 * 60
    return api_client

# 定时刷新数据
def refresh_data():
    while True:
        try:
            client = get_api_client()
            # 调用API获取数据
            global voting_data
            voting_data = client.get_voting_results()
        except Exception as e:
            print(f"刷新数据失败: {e}")
        # 每6秒刷新一次数据
        time.sleep(6)

# 启动数据刷新线程
def start_refresh_thread():
    thread = threading.Thread(target=refresh_data)
    thread.daemon = True
    thread.start()

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/admin')
def admin():
    return render_template('admin.html')

@app.route('/api/voting_data')
def get_voting_data():
    return jsonify(voting_data)

@app.route('/api/voting_data/<round_num>')
def get_voting_data_by_round(round_num):
    # 根据轮次获取数据
    if round_num in voting_data:
        return jsonify(voting_data[round_num])
    return jsonify({}), 404

@app.route('/api/voting_data/all')
def get_all_voting_data():
    # 获取所有选手数据（用于最后一轮）
    all_contestants = {}
    for round_data in voting_data.values():
        all_contestants.update(round_data)
    return jsonify(all_contestants)

if __name__ == '__main__':
    # 确保utils目录存在
    if not os.path.exists('utils'):
        os.makedirs('utils')
    # 启动数据刷新线程
    start_refresh_thread()
    # 运行应用
    app.run(debug=True, host='0.0.0.0', port=5000)